<template>
  <div class="task-list">
    <div class="page-header">
      <div class="header-left">
        <h1>任务管理</h1>
        <p>管理和跟踪所有任务</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="createTask">
          <el-icon><Plus /></el-icon>
          创建任务
        </el-button>
      </div>
    </div>
    
    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-input
          v-model="searchQuery"
          placeholder="搜索任务标题或描述"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="filter-right">
        <el-select
          v-model="statusFilter"
          placeholder="任务状态"
          style="width: 120px"
          clearable
          @change="handleFilter"
        >
          <el-option label="待开始" value="待开始" />
          <el-option label="进行中" value="进行中" />
          <el-option label="已完成" value="已完成" />
          <el-option label="已暂停" value="已暂停" />
          <el-option label="已取消" value="已取消" />
        </el-select>
        
        <el-select
          v-model="priorityFilter"
          placeholder="优先级"
          style="width: 100px"
          clearable
          @change="handleFilter"
        >
          <el-option label="高" value="high" />
          <el-option label="中" value="medium" />
          <el-option label="低" value="low" />
        </el-select>
        
        <el-select
          v-model="projectFilter"
          placeholder="所属项目"
          style="width: 150px"
          clearable
          @change="handleFilter"
        >
          <el-option
            v-for="project in projects"
            :key="project.id"
            :label="project.name"
            :value="project.id"
          />
        </el-select>
        
        <el-button @click="resetFilters">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </div>
    </div>
    
    <!-- 视图切换 -->
    <div class="view-controls">
      <el-radio-group v-model="viewMode" @change="handleViewChange">
        <el-radio-button label="list">列表视图</el-radio-button>
        <el-radio-button label="board">看板视图</el-radio-button>
      </el-radio-group>
    </div>
    
    <!-- 列表视图 -->
    <div v-if="viewMode === 'list'" class="list-view" v-loading="loading">
      <el-table
        :data="filteredTasks"
        style="width: 100%"
        @row-click="viewTask"
        row-class-name="task-row"
      >
        <el-table-column prop="title" label="任务标题" min-width="200">
          <template #default="{ row }">
            <div class="task-title">
              <div class="priority-indicator" :class="row.priority"></div>
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="project" label="所属项目" width="150">
          <template #default="{ row }">
            <el-tag size="small" effect="plain">
              {{ row.project?.name || '未分配' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="assignee" label="负责人" width="120">
          <template #default="{ row }">
            <div class="assignee-info" v-if="row.assignee">
              <el-avatar :size="24">
                {{ row.assignee.username.charAt(0).toUpperCase() }}
              </el-avatar>
              <span>{{ row.assignee.username }}</span>
            </div>
            <span v-else class="unassigned">未分配</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="{ row }">
            <el-tag
              :type="getPriorityType(row.priority)"
              size="small"
              effect="plain"
            >
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="dueDate" label="截止日期" width="120">
          <template #default="{ row }">
            <span :class="{ 'overdue': isOverdue(row.dueDate) }">
              {{ formatDate(row.dueDate) }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-dropdown @command="handleCommand">
              <el-button text>
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'view', id: row.id }">
                    <el-icon><View /></el-icon>
                    查看详情
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'edit', id: row.id }">
                    <el-icon><Edit /></el-icon>
                    编辑任务
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'assign', id: row.id }">
                    <el-icon><User /></el-icon>
                    分配任务
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{ action: 'delete', id: row.id }"
                    divided
                  >
                    <el-icon><Delete /></el-icon>
                    删除任务
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 看板视图 -->
    <div v-else class="board-view" v-loading="loading">
      <div class="board-columns">
        <div class="board-column" v-for="status in taskStatuses" :key="status">
          <div class="column-header">
            <h3>{{ status }}</h3>
            <el-badge :value="getTaskCountByStatus(status)" class="item" />
          </div>
          <div class="column-content">
            <div
              class="task-card"
              v-for="task in getTasksByStatus(status)"
              :key="task.id"
              @click="viewTask(task)"
            >
              <div class="task-card-header">
                <div class="task-priority" :class="task.priority"></div>
                <el-dropdown @command="handleCommand">
                  <el-button text size="small">
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="{ action: 'view', id: task.id }">
                        查看详情
                      </el-dropdown-item>
                      <el-dropdown-item :command="{ action: 'edit', id: task.id }">
                        编辑任务
                      </el-dropdown-item>
                      <el-dropdown-item :command="{ action: 'delete', id: task.id }" divided>
                        删除任务
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              
              <div class="task-card-content">
                <h4>{{ task.title }}</h4>
                <p>{{ task.description }}</p>
                
                <div class="task-card-meta">
                  <div class="task-project" v-if="task.project">
                    <el-tag size="small" effect="plain">
                      {{ task.project.name }}
                    </el-tag>
                  </div>
                  
                  <div class="task-assignee" v-if="task.assignee">
                    <el-avatar :size="20">
                      {{ task.assignee.username.charAt(0).toUpperCase() }}
                    </el-avatar>
                    <span>{{ task.assignee.username }}</span>
                  </div>
                  
                  <div class="task-due-date">
                    <el-icon><Calendar /></el-icon>
                    <span :class="{ 'overdue': isOverdue(task.dueDate) }">
                      {{ formatDate(task.dueDate) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div class="empty-state" v-if="!loading && filteredTasks.length === 0">
      <el-empty description="暂无任务数据">
        <el-button type="primary" @click="createTask">
          创建第一个任务
        </el-button>
      </el-empty>
    </div>
    
    <!-- 分页 -->
    <div class="pagination" v-if="viewMode === 'list' && filteredTasks.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import {
  Plus,
  Search,
  Refresh,
  MoreFilled,
  View,
  Edit,
  Delete,
  User,
  Calendar
} from '@element-plus/icons-vue'

const router = useRouter()

const loading = ref(false)
const viewMode = ref('list')
const searchQuery = ref('')
const statusFilter = ref('')
const priorityFilter = ref('')
const projectFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 任务状态列表
const taskStatuses = ['待开始', '进行中', '已完成', '已暂停', '已取消']

// 项目列表
const projects = ref([
  { id: 1, name: '项目管理系统' },
  { id: 2, name: '电商平台' },
  { id: 3, name: '移动应用开发' }
])

// 模拟任务数据
const tasks = ref([
  {
    id: 1,
    title: '实现用户认证功能',
    description: '完成用户登录、注册和权限验证功能',
    status: '进行中',
    priority: 'high',
    dueDate: new Date(Date.now() + 1000 * 60 * 60 * 24 * 3),
    project: { id: 1, name: '项目管理系统' },
    assignee: { id: 1, username: '张三' },
    createdAt: new Date('2024-01-15')
  },
  {
    id: 2,
    title: '设计数据库表结构',
    description: '设计用户、项目、任务等核心表结构',
    status: '已完成',
    priority: 'medium',
    dueDate: new Date(Date.now() - 1000 * 60 * 60 * 24),
    project: { id: 1, name: '项目管理系统' },
    assignee: { id: 2, username: '李四' },
    createdAt: new Date('2024-01-10')
  },
  {
    id: 3,
    title: '前端页面开发',
    description: '开发项目管理相关的前端页面',
    status: '待开始',
    priority: 'medium',
    dueDate: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7),
    project: { id: 1, name: '项目管理系统' },
    assignee: { id: 3, username: '王五' },
    createdAt: new Date('2024-01-12')
  },
  {
    id: 4,
    title: 'API接口开发',
    description: '开发后端API接口',
    status: '进行中',
    priority: 'high',
    dueDate: new Date(Date.now() + 1000 * 60 * 60 * 24 * 5),
    project: { id: 1, name: '项目管理系统' },
    assignee: { id: 1, username: '张三' },
    createdAt: new Date('2024-01-14')
  },
  {
    id: 5,
    title: '系统测试',
    description: '进行系统功能测试和性能测试',
    status: '待开始',
    priority: 'low',
    dueDate: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14),
    project: { id: 1, name: '项目管理系统' },
    assignee: null,
    createdAt: new Date('2024-01-16')
  }
])

// 过滤后的任务列表
const filteredTasks = computed(() => {
  let result = tasks.value
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(task => 
      task.title.toLowerCase().includes(query) ||
      (task.description && task.description.toLowerCase().includes(query))
    )
  }
  
  // 状态过滤
  if (statusFilter.value) {
    result = result.filter(task => task.status === statusFilter.value)
  }
  
  // 优先级过滤
  if (priorityFilter.value) {
    result = result.filter(task => task.priority === priorityFilter.value)
  }
  
  // 项目过滤
  if (projectFilter.value) {
    result = result.filter(task => task.project?.id === Number(projectFilter.value))
  }
  
  total.value = result.length
  
  // 分页（仅列表视图）
  if (viewMode.value === 'list') {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return result.slice(start, end)
  }
  
  return result
})

// 根据状态获取任务
const getTasksByStatus = (status: string) => {
  return filteredTasks.value.filter(task => task.status === status)
}

// 根据状态获取任务数量
const getTaskCountByStatus = (status: string) => {
  return getTasksByStatus(status).length
}

// 获取状态类型
const getStatusType = (status: string): 'success' | 'warning' | 'danger' | 'info' | 'primary' => {
  const types: Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'> = {
    '待开始': 'info',
    '进行中': 'warning',
    '已完成': 'success',
    '已暂停': 'info',
    '已取消': 'danger'
  }
  return types[status] || 'info'
}

// 获取优先级类型
const getPriorityType = (priority: string): 'success' | 'warning' | 'danger' | 'info' | 'primary' => {
  const types: Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'> = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'success'
  }
  return types[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const texts: Record<string, string> = {
    'high': '高',
    'medium': '中',
    'low': '低'
  }
  return texts[priority] || priority
}

// 格式化日期
const formatDate = (date: Date) => {
  return dayjs(date).format('MM-DD')
}

// 检查是否过期
const isOverdue = (date: Date) => {
  return dayjs(date).isBefore(dayjs(), 'day')
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
}

// 重置筛选
const resetFilters = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  priorityFilter.value = ''
  projectFilter.value = ''
  currentPage.value = 1
}

// 视图切换
const handleViewChange = () => {
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 操作处理
const handleCommand = (command: { action: string; id: number }) => {
  const { action, id } = command
  
  switch (action) {
    case 'view':
      viewTaskById(id)
      break
    case 'edit':
      editTask(id)
      break
    case 'assign':
      assignTask()
      break
    case 'delete':
      deleteTask(id)
      break
  }
}

// 查看任务
const viewTask = (task: any) => {
  router.push(`/tasks/${task.id}`)
}

const viewTaskById = (id: number) => {
  router.push(`/tasks/${id}`)
}

// 编辑任务
const editTask = (id: number) => {
  router.push(`/tasks/${id}/edit`)
}

// 分配任务
const assignTask = () => {
  ElMessage.info('任务分配功能开发中...')
}

// 删除任务
const deleteTask = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个任务吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    tasks.value = tasks.value.filter(t => t.id !== id)
    ElMessage.success('任务删除成功')
  } catch {
    // 用户取消删除
  }
}

// 创建任务
const createTask = () => {
  router.push('/tasks/create')
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 这里应该调用API加载任务数据
    // await taskStore.fetchTasks()
    await new Promise(resolve => setTimeout(resolve, 500))
  } catch (error) {
    console.error('加载任务数据失败:', error)
    ElMessage.error('加载任务数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.task-list {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-right {
  display: flex;
  gap: 12px;
}

.view-controls {
  margin-bottom: 24px;
}

.list-view {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.task-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.priority-indicator {
  width: 4px;
  height: 16px;
  border-radius: 2px;
}

.priority-indicator.high {
  background: #f56c6c;
}

.priority-indicator.medium {
  background: #e6a23c;
}

.priority-indicator.low {
  background: #67c23a;
}

.assignee-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.unassigned {
  color: #999;
  font-style: italic;
}

.overdue {
  color: #f56c6c;
  font-weight: 600;
}

:deep(.task-row) {
  cursor: pointer;
}

:deep(.task-row:hover) {
  background-color: #f5f7fa;
}

.board-view {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
  min-height: 600px;
}

.board-columns {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
  height: 100%;
}

.board-column {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.column-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e6e6e6;
}

.column-header h3 {
  margin: 0;
  font-size: 14px;
  color: #333;
  font-weight: 600;
}

.column-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: 400px;
}

.task-card {
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.task-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.task-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.task-priority {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.task-priority.high {
  background: #f56c6c;
}

.task-priority.medium {
  background: #e6a23c;
}

.task-priority.low {
  background: #67c23a;
}

.task-card-content h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
  font-weight: 600;
}

.task-card-content p {
  margin: 0 0 12px 0;
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.task-card-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.task-project {
  font-size: 12px;
}

.task-assignee {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #666;
}

.task-due-date {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .board-columns {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-section {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-right {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .board-columns {
    grid-template-columns: 1fr;
  }
}
</style>